package cn.mxz.xmu.robots.pojo;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wang.mouge.cache.client.DeprecatedRedisLibrary;
import cn.mxz.xmu.interfaces.dubbo.Debug;

/**
 * 在获取教务之前，根据学校ID，获取这个学校的配置信息，并且传递给教务机器人；
 * 内部维护了一个学校配置信息的缓存，当缓存学校超过400的时候，会自动清空缓存。
 * 
 * @author kangbin <kangbin@mouge.wang>
 * @since 2015-03-12
 */
public final class SchoolFactory
{
	private static Logger LOG = LoggerFactory.getLogger(SchoolFactory.class);

	/**
	 * 根据学校ID获取学校配置信息，做了二级缓存，先从内存中获取学校配置信息，如果有，则直接返回；
	 * 否则的话，从NoSQL中查找缓存，有的话，返回并且更新内存，否则，从数据库中拉取配置信息
	 * 
	 * @param schoolId
	 *            学校ID
	 * @return 学校的配置信息
	 */
	public static School createSchool(String schoolId)
	{
		String key = "university_" + schoolId;
		String schoolString = null;

		try
		{
			if (!Debug.console_value)
			{
				schoolString = JSONObject.fromObject(DeprecatedRedisLibrary.hgetAll(key)).toString();
			}
			else
			{
				schoolString = JSONObject.fromObject(DeprecatedRedisLibrary.hgetAll(key)).toString();
			}
		}
		catch (Exception e)
		{
			LOG.error("Redis Exception ==> " + e.getMessage());
		}

		/* 网络传输过程中，会传输UTF-8带有BOM头，在这里手动去除BOM头，否则，JSON解析或出现错误 */
		if (schoolString.startsWith("\uFEFF"))
		{
			schoolString = schoolString.substring(1);
		}

		School school = string2School(schoolString);

		return school;
	}

	/**
	 * edu将一个JSON字符串转换为一个School对象
	 * 
	 * @param schoolInfo
	 *            JSON字符串
	 * @return School对象
	 */
	private static School string2School(String schoolInfo)
	{
		// Logger logger = LoggerFactory.getLogger(UniversityPreProcess.class);
		// logger.info(schoolInfo);

		School school = new School();
		JSONObject json = JSONObject.fromObject(schoolInfo);
		JSONObject eduObject = JSONObject.fromObject(json.getString("edu"));
		JSONObject libObject = JSONObject.fromObject(json.getString("lib"));
		JSONObject portalObject = JSONObject.fromObject(json.getString("portal"));

		LOG.info("schoolName: " + json.getString("name") + " schoolID: " + json.getString("id"));

		school.setId(json.getString("id"));
		school.setName(json.getString("name"));
		school.setEduObject(eduObject);
		school.setLibObject(libObject);
		school.setPortalObject(portalObject);

		return school;
	}
}
